<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <% htmlTitle = "选择书籍" %>
    <%- include("./header.html"); %>
    <style>
        .main {
            width: 92vw !important;
            max-width: initial !important;
        }

        #book-table {
            width: 100%;
            margin-top: 30px;
            line-height: 2.3em;
        }

        table, tr, th, td {
            border: 1px solid black;
        }

        tr {
            white-space: nowrap;
        }

        tr:hover {
            background-color: #f5f5f5;
        }

        tr a {
            cursor: pointer;
        }
    </style>
</head>
<body>
    <!-- 获取参数 -->
    <script src="/assets/javascripts/getParams.js"></script>
    <!-- 渲染表格 -->
    <script src="/assets/javascripts/renderTable.js"></script>
    <main class="main">
        <input id="searchInput" type="text" />
        <input id="searchButton" type="button" value="搜索" />
            <table id="book-table"></table>
        </div>
        <button onclick="closeWindow();" style="position: fixed; right: 0; top: 0;">×</button>
    </main>
    <!-- 搜索书籍 -->
    <script>
        var requestParams = getParams();
        var searchbox = document.getElementById("searchInput");
        var keyword = (requestParams["keyword"] || "").trim();
        search({
            tableElementId: "book-table",
            searchText: null,
            categoryId: null
        });

        $("#searchButton").click(function () {
            search({
                tableElementId: "book-table",
                searchText: $("#searchInput").val(),
                categoryId: null
            });
        });

        function search({ tableElementId = "", searchText = "", categoryId = 0 }) {
            getRequest("/book/search", { bookName: searchText, categoryId: categoryId })
                .then(function (responseData) {
                    var axiosData = responseData.data;
                    var status = axiosData.status;
                    var data = axiosData.data;
                    if (status === "success") {
                        // console.log(data)

                        // 数据进行转换
                        var renderData = [];
                        data.forEach(element => {
                            var mainDivWidth = 96/*vw*/; // 定义div的宽度（用于计算表格中的数据的显示长度）
                            var columnWidth = [20, 15, 10, 15, 5, 35];
                            renderData.push({
                                编号: `${element.id}`,
                                管理: `<span class="overflow-omit" style="max-width: ${columnWidth[5] * mainDivWidth / 100}vw; max-height: 2em; margin: 0 auto;">
                                            <a href="javascript:selectItem(${element.id});">选择</a>
                                        </span>`,
                                书名: `<a target="_blank" href="/book?id=${element.id}">
                                            <span class="overflow-omit" style="max-width: ${columnWidth[0] * mainDivWidth / 100}vw; max-height: 2em; margin: 0 auto;">
                                                ${element.bookName}
                                            </span>
                                        </a>`,
                                分类: `<a target="_blank" href="/category?id=${element.category.id}">
                                            <span class="overflow-omit" style="max-width: ${columnWidth[1] * mainDivWidth / 100}vw; max-height: 2em; margin: 0 auto;">
                                                ${element.category.name}
                                            </span>
                                        </a>`,
                                作者: `${element.author}`,
                                语言: `<span class="overflow-omit" style="max-width: ${columnWidth[2] * mainDivWidth / 100}vw; max-height: 2em; margin: 0 auto;">
                                            ${element.language}
                                        </span>`,
                                出版社: `<span class="overflow-omit" style="max-width: ${columnWidth[3] * mainDivWidth / 100}vw; max-height: 2em; margin: 0 auto;">
                                            ${element.publishingHouse}
                                        </span>`,
                                来源: `<span class="overflow-omit" style="max-width: ${columnWidth[4] * mainDivWidth / 100}vw; max-height: 2em; margin: 0 auto;">
                                            ${element.publishingHouse}
                                        </span>`,
                            })
                        });

                        if (renderData.length == 0) {
                            console.log("没有搜索到相关书籍");
                            function htmlEncode(str) {
                                // refer: https://stackoverflow.com/questions/4183801/escape-html-chracters
                                var div = document.createElement('div');
                                var txt = document.createTextNode(str);
                                div.appendChild(txt);
                                return div.innerHTML;
                            }
                            if (searchText && searchText != "") {
                                //
                                renderTable({ data: `没有搜索到与 <span style="color: red;">${htmlEncode(searchText)}</span> 相关的书籍，请换个关键词再试试吧`, tableId: tableElementId, renderTableHead: true });
                            } else if (categoryId && categoryId != 0) {
                                //
                                renderTable({ data: `该分类下暂无电子书`, tableId: tableElementId, renderTableHead: true });
                            }
                        } else {
                            renderTable({ data: renderData, tableId: tableElementId, renderTableHead: true });
                        }
                    } else {
                        swal(`出错啦！${data.errMsg} (错误码: ${data.errCode})`);
                    }
                }).catch(function (error) {
                    console.log(error);
                    swal("无法连接到服务器，请检查网络连接！");
                });
        }

        function selectItem(id) {
            window.parent.postMessage(JSON.stringify({
                id: id,
                iframe: "book-selector"
            }), "*");
        }

        function closeWindow() {
            window.parent.postMessage(JSON.stringify({
                id: null,
                iframe: "book-selector"
            }), "*");
        }
    </script>
</body>
</html>